<template>
  <div>
    <div v-if="edit">
      <Cell v-if="dataRecord2One" is-link :title="dataRecord2One[0].value.display_name" @click="showPopup = true"/>
      <Cell v-else is-link title="请选择" @click="showPopup = true"/>

    </div>
    <div v-else>
      <router-link style="alignment:center"
                   v-if="dataRecord2One && enjump"
                   :to="{name:'EditForm',params:{model:field.relation,id:dataRecord2One[0].value.display_name}}"
      >{{ dataRecord2One[0].value.display_name }}
      </router-link>
      <div v-else-if="dataRecord2One&&dataRecord2One[0].value.display_name">{{ dataRecord2One[0].value.display_name }}
      </div>
      <div v-else>无</div>
    </div>
    <Many v-if="widget==='table'" :showPopup.sync="showPopup" :model="model" :id="id" :field="field"
          @select="onchange"></Many>
    <ActionSheet v-if="widget==='simple'" v-model="showPopup" :actions="actions" @select="onchange" cancel-text="取消"
                 close-on-click-action></ActionSheet>
  </div>
</template>

<script>
  import Vue from 'vue'
  import gql from 'graphql-tag'
  import {ActionSheet, Cell} from 'vant';
  import Many from '../ctrls/Many'

  export default {
    name: 'Many2one',
    components: {
      Many, ActionSheet, Cell
    },
    props: {
      field: {
        type: Object,
        default() {
          return {}
        }
      },
      model: {type: String, default: ''},
      id: {type: Number, default: 0},
      saveFast: {type: Boolean, default: true},
      edit: {type: Boolean, default: false},
      enjump: {type: Boolean, default: true},
      widget: {type: String, default: 'table'}
    },
    inject: ['getValue'],
    data: function () {
      return {
        searchText: '',
        showPopup: false,
        tablePage: {
          currentPage: 1,
          pageSize: 10
        },
        order: '',
        domain: this.field.domain,
        newval: this.getValue().cval,
        allRecord: []
      }
    },
    computed: {
      value() {
        return this.getValue()
      },
      actions() {
        let v = []
        for (let item of this.allRecord) {
          let d = {name: item.value.display_name, id: item.value.id}
          v.push(d)
        }
        return v
      }
    },
    apollo: {
      dataRecord2One() {
        return {
          query: gql`query qdv($model:String,$id:Int!,$queryFields:[String]){
                   dataRecord2One:allRecord(model:$model,id:$id,fields:$queryFields){
            value
          }
         }`,
          variables() {
            return {
              model: this.field.relation,
              id: this.newval,
              queryFields: ['id', 'display_name']
            }
          },
          skip() {
            return !(this.field.relation && typeof this.newval === 'number')
          }
        }
      },
      allRecord: {
        query: gql`query qdv($model:String,$domain:String!,$queryFields:[String],$order:String,$limit:Int,$offset:Int){
                   allRecord:allRecord(model:$model,domain:$domain,fields:$queryFields,order:$order,limit:$limit,offset:$offset){
            value
          }
         }`,
        variables() {
          return {
            model: this.field.relation,
            domain: JSON.stringify(this.domain),
            offset: ((this.tablePage.currentPage - 1) * this.tablePage.pageSize) || 0,
            order: this.order,
            limit: this.tablePage.pageSize,
            queryFields: ['id', 'display_name']
          }
        },
        skip() {
          return !(this.showPopup && this.field.relation)
        }
      }
    },
    mounted: function () {
      // this.getNewData()
    },
    methods: {
      extend: function (obj, src) {
        for (var key in src) {
          if (src.hasOwnProperty(key)) obj[key] = src[key]
        }
        return obj
      }, writeDict() {
        let v = {}
        v[this.field.name] = this.newval
        return v
      },
      onchange: function (action, index) {
        this.newval = action.id || action.value.id   //从Many.vue调用过来的参数
        if (this.saveFast) {
          let self = this
          this.$apollo.mutate({
            mutation: gql`mutation($id:Int!,$model:String!,$value:JSON!){
  writeRecord(id:$id,model:$model,value:$value){
    ok
  }
}`,
            variables: {id: this.id, model: this.model, value: this.writeDict()}
          }).then(function (response) {
            if (response && response.data.writeRecord.ok) {
              self.$apollo.queries.dataRecord2One.refetch({
                model: self.field.relation,
                id: self.newval,
                queryFields: ['id', 'display_name']
              })
              // self.app_root.toast(response.result.errMsg)
              // self.$router ? self.$router.back() : window.history.back()
            } else if (response && !response.data.writeRecord.ok) {
              // self.app_root.toast(response.result.errMsg)
            }
          })
            .catch(function (error) {
              console.log(error, __filename)
            })
        } else {
          Vue.set(this.value, 'newval', this.newval)
          Vue.set(this.value, 'change', this.value.cval !== this.newval)
        }
        this.showPopup = false
      },
      show: function () {
        this.getNewData()
        this.showPopup = true
      },
      onSubmit: function (txt) {
        // this.getNewData()
      },
      getNewData: function () {
        this.domain = [["name", "ilike", this.searchText]]  //JSON.parse( this.field.domain).append 字符串
      }
    }
  }
</script>

<style type="less">
  .flex {
    display: flex;
  }

  .vux-popup-radio-popup {
    background-color: #fff;
  }
</style>
